package com.idp.demo.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.idp.common.error.SystemException;
import com.idp.common.utils.RedissonUtil;
import com.idp.demo.dto.GoodsDto;
import com.idp.demo.entity.GoodsEntity;
import com.idp.demo.mapper.GoodsMapper;
import com.idp.demo.service.GoodsOrderService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GoodsOrderServiceImpl implements GoodsOrderService {

	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
//	public synchronized void createOrder(GoodsDto goodsDto) {
	public void createOrder(GoodsDto goodsDto) {

		RLock lock = RedissonUtil.getLock("goodsId"+goodsDto.getId());

		if(lock.tryLock()) {

			try {

				GoodsEntity goods = goodsMapper.selectById(goodsDto.getId());

				if(goods != null) {

					System.err.println(goods.getRemainCount());

					if(goods.getRemainCount() > 0) {

						goods.setSellCount(goods.getSellCount()+1);
						goods.setRemainCount(goods.getRemainCount()-1);

						goodsMapper.updateById(goods);
					}
					else {

						throw new SystemException("下单失败，库存不足");
					}
				}
				else {

					throw new SystemException("下单失败，商品已下架");
				}
			} catch (Exception e) {

				throw e;
			} finally {

				lock.unlock();
			}
		}
		else {

			ThreadUtil.sleep(200);

			this.createOrder(goodsDto);
		}

	}

}
